package cn.ly.core.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchTest {
	
	public static void main(String[] args) throws InterruptedException {
		final CountDownLatch begin = new CountDownLatch(1);
		final CountDownLatch end = new CountDownLatch(10);//初始化一个10个计数器的CountDownLatch，CountDownLatch内部有一个计数器
		
		final ExecutorService service = Executors.newFixedThreadPool(4);
		
		for(int index=0; index<10; index++){
			final int NO = index + 1;
			service.submit(new Runnable(){
				public void run() {
					try {
						begin.await();                  //使当前线程在锁存器倒计数至零之前一直等待
						Thread.sleep((int)(Math.random()*10000));
						System.out.println("No." + NO + " arrived");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}finally{
						end.countDown();                //让end这个CountDownLatch计数器减一
					}
				}
			});
		}
		System.out.println("Game Start");
		begin.countDown();                       //让begin这个CountDownLatch的计数器减一（初始化为1），所以变成0，上面的线程开始执行
		end.await();                             //等待上面的所有线程每次运行完减一，直到end的计数器为0，当前线程才能技术执行，否则一直等待
		System.out.println("Game Over");         
		service.shutdown();                      /**
												  * 这个方法和Thread.yield()效果类似，但是yeild方法，当前线程有可能继续争抢cpu
												  * 但是CountDownLatch则是一直等待，不争抢cpu资源，也不必执行while循环，效率更高
												  * 
												 */
		
	}

}
